package com.tju.ocean_ecology_website.controller;

import com.tju.ocean_ecology_website.dto.ApiResponse;
import com.tju.ocean_ecology_website.dto.HoursRecordDTO;
import com.tju.ocean_ecology_website.dto.PageResult;
import com.tju.ocean_ecology_website.dto.ProjectDTO;
import com.tju.ocean_ecology_website.dto.ProjectRatingDTO;
import com.tju.ocean_ecology_website.dto.ProjectRatingRequestDTO;
import com.tju.ocean_ecology_website.dto.ProjectRatingResponseDTO;
import com.tju.ocean_ecology_website.dto.ProjectStatsDTO;
import com.tju.ocean_ecology_website.dto.ServiceHoursDTO;
import com.tju.ocean_ecology_website.dto.ServiceHoursResponseDTO;
import com.tju.ocean_ecology_website.entity.Activity;
import com.tju.ocean_ecology_website.entity.ActivityFeedback;
import com.tju.ocean_ecology_website.entity.ActivitySignup;
import com.tju.ocean_ecology_website.entity.User;
import com.tju.ocean_ecology_website.entity.VolunteerInfo;
import com.tju.ocean_ecology_website.entity.VolunteerServiceRecord;
import com.tju.ocean_ecology_website.mapper.UserMapper;
import com.tju.ocean_ecology_website.service.ActivityFeedbackService;
import com.tju.ocean_ecology_website.service.ActivityService;
import com.tju.ocean_ecology_website.service.ActivitySignupService;
import com.tju.ocean_ecology_website.service.UserService;
import com.tju.ocean_ecology_website.service.VolunteerInfoService;
import com.tju.ocean_ecology_website.service.VolunteerServiceRecordService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 志愿者项目控制器
 */
@RestController
@RequestMapping("/api/volunteer")
public class VolunteerProjectsController {

    @Resource
    private UserService userService;

    @Resource
    private VolunteerInfoService volunteerInfoService;

    @Resource
    private ActivityService activityService;

    @Resource
    private ActivitySignupService activitySignupService;

    @Resource
    private ActivityFeedbackService activityFeedbackService;

    @Resource
    private VolunteerServiceRecordService volunteerServiceRecordService;

    @Resource
    private UserMapper userMapper;

    /**
     * 获取志愿者项目列表
     *
     * @param page 页码
     * @param pageSize 每页大小
     * @param status 状态：0-未开始 1-报名中 2-进行中 3-已结束
     * @param onlyJoined 是否只显示已报名的项目
     * @return 项目列表
     */
    @GetMapping("/projects")
    public ResponseEntity<ApiResponse<PageResult<ProjectDTO>>> getVolunteerProjects(
            @RequestParam(value = "page", defaultValue = "1") Integer page,
            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "onlyJoined", defaultValue = "true") Boolean onlyJoined) {

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询用户已报名的活动ID列表
        List<Long> userJoinedActivityIds = new ArrayList<>();
        if (onlyJoined) {
            ActivitySignup signupQuery = new ActivitySignup();
            signupQuery.setUserId(currentUserId);
            // 只查询状态为已通过的报名记录
            signupQuery.setStatus(1);
            List<ActivitySignup> userSignups = activitySignupService.queryAll(signupQuery);
            userJoinedActivityIds = userSignups.stream()
                    .map(ActivitySignup::getActivityId)
                    .collect(Collectors.toList());

            // 如果用户没有报名任何活动，返回空结果
            if (userJoinedActivityIds.isEmpty()) {
                PageResult<ProjectDTO> emptyResult = new PageResult<>();
                emptyResult.setList(new ArrayList<>());
                emptyResult.setTotal(0);
                emptyResult.setPage(page);
                emptyResult.setPageSize(pageSize);
                emptyResult.setPages(0);
                return ResponseEntity.ok(ApiResponse.success(emptyResult));
            }
        }

        // 查询活动列表
        Activity activityQuery = new Activity();
        if (status != null) {
            activityQuery.setStatus(status);
        }

        // 设置审核状态为已通过
        activityQuery.setAuditStatus(1);

        Page<Activity> activityPage;
        PageRequest pageRequest = PageRequest.of(page - 1, pageSize);

        if (onlyJoined && !userJoinedActivityIds.isEmpty()) {
            // 只查询用户已报名的活动
            activityPage = activityService.queryByPageAndIds(activityQuery, userJoinedActivityIds, pageRequest);
        } else if (!onlyJoined) {
            // 查询所有符合条件的活动
            activityPage = activityService.queryByPage(activityQuery, pageRequest);
        } else {
            // 用户选择只看已报名但没有报名任何活动，返回空页
            activityPage = Page.empty(pageRequest);
        }

        // 转换为DTO
        List<ProjectDTO> projectDTOs = activityPage.getContent().stream().map(activity -> {
            ProjectDTO dto = ProjectDTO.fromActivity(activity);

            // 查询用户报名信息
            ActivitySignup signupQuery = new ActivitySignup();
            signupQuery.setActivityId(activity.getId());
            signupQuery.setUserId(currentUserId);
            Page<ActivitySignup> signupPage = activitySignupService.queryByPage(signupQuery, PageRequest.of(0, 1));

            if (!signupPage.isEmpty()) {
                ActivitySignup signup = signupPage.getContent().get(0);
                dto.setJoinTime(signup.getSignupTime());
                // 移除签到签退相关字段
            }

            // 查询用户评分
            ActivityFeedback feedbackQuery = activityFeedbackService.queryByUserAndActivity(currentUserId, activity.getId());
            if (feedbackQuery != null) {
                dto.setMyRating(feedbackQuery.getSatisfaction());
            }

            // 查询用户服务时长 - 累加所有服务记录的时长
            VolunteerServiceRecord recordQuery = new VolunteerServiceRecord();
            recordQuery.setActivityId(activity.getId());
            recordQuery.setVolunteerId(currentUserId);
            // 获取所有服务记录
            List<VolunteerServiceRecord> serviceRecords = volunteerServiceRecordService.queryAll(recordQuery);

            // 累加服务时长（只计算已通过的记录）
            int totalHours = 0;
            for (VolunteerServiceRecord record : serviceRecords) {
                if (record.getStatus() != null && record.getStatus() == 1 && record.getServiceHours() != null) {
                    totalHours += record.getServiceHours();
                }
            }

            // 将小时转换为分钟
            dto.setMyDuration(totalHours * 60);

            return dto;
        }).collect(Collectors.toList());

        // 创建分页结果
        PageResult<ProjectDTO> pageResult = new PageResult<>();
        pageResult.setList(projectDTOs);
        pageResult.setTotal(activityPage.getTotalElements());
        pageResult.setPage(page);
        pageResult.setPageSize(pageSize);
        pageResult.setPages(activityPage.getTotalPages());

        return ResponseEntity.ok(ApiResponse.success(pageResult));
    }

    /**
     * 获取项目详情
     *
     * @param id 项目ID
     * @return 项目详情
     */
    @GetMapping("/projects/{id}")
    public ResponseEntity<ApiResponse<ProjectDTO>> getProjectDetail(@PathVariable("id") Long id) {
        // 查询活动信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 转换为DTO
        ProjectDTO dto = ProjectDTO.fromActivity(activity);

        // 查询用户报名信息
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setActivityId(activity.getId());
        signupQuery.setUserId(currentUserId);
        Page<ActivitySignup> signupPage = activitySignupService.queryByPage(signupQuery, PageRequest.of(0, 1));

        if (!signupPage.isEmpty()) {
            ActivitySignup signup = signupPage.getContent().get(0);
            dto.setJoinTime(signup.getSignupTime());
        }

        // 查询用户评分
        ActivityFeedback feedbackQuery = activityFeedbackService.queryByUserAndActivity(currentUserId, activity.getId());
        if (feedbackQuery != null) {
            dto.setMyRating(feedbackQuery.getSatisfaction());
        }

        // 查询用户服务时长 - 累加所有服务记录的时长
        VolunteerServiceRecord recordQuery = new VolunteerServiceRecord();
        recordQuery.setActivityId(activity.getId());
        recordQuery.setVolunteerId(currentUserId);
        // 获取所有服务记录
        List<VolunteerServiceRecord> serviceRecords = volunteerServiceRecordService.queryAll(recordQuery);

        // 累加服务时长（只计算已通过的记录）
        int totalHours = 0;
        for (VolunteerServiceRecord record : serviceRecords) {
            if (record.getStatus() != null && record.getStatus() == 1 && record.getServiceHours() != null) {
                totalHours += record.getServiceHours();
            }
        }

        // 将小时转换为分钟
        dto.setMyDuration(totalHours * 60);

        // 查询服务时长记录列表 - 使用已有的serviceRecords变量
        // 不需要重新查询，因为我们已经在上面获取了所有服务记录

        // 转换为DTO
        List<HoursRecordDTO> hoursRecordDTOs = serviceRecords.stream()
                .map(HoursRecordDTO::fromServiceRecord)
                .collect(Collectors.toList());
        dto.setHoursRecords(hoursRecordDTOs);

        // 设置是否有证书（这里简化处理，实际应该根据项目配置或其他条件决定）
        // 假设当服务时长超过10小时时有证书
        dto.setCertificate(dto.getMyDuration() != null && dto.getMyDuration() >= 600); // 10小时 = 600分钟

        return ResponseEntity.ok(ApiResponse.success(dto));
    }

    /**
     * 参与项目
     *
     * @param id 项目ID
     * @return 参与结果
     */
    @PostMapping("/projects/{id}/join")
    public ResponseEntity<ApiResponse<ActivitySignup>> joinProject(@PathVariable("id") Long id) {

        // 查询活动信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }

        // 检查活动状态
        if (activity.getStatus() != 0) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目已开始或已结束，无法参与"));
        }

        // 创建报名记录
        ActivitySignup signup = new ActivitySignup();
        signup.setActivityId(id);
        signup.setStatus(0); // 待审核
        signup.setSignupTime(new Date());

        // 保存报名记录
        ActivitySignup savedSignup = activitySignupService.insert(signup);

        return ResponseEntity.ok(ApiResponse.success(savedSignup, "参与项目成功，等待审核"));
    }

    /**
     * 退出项目
     *
     * @param id 项目ID
     * @return 退出结果
     */
    @PostMapping("/projects/{id}/quit")
    public ResponseEntity<ApiResponse<Boolean>> quitProject(@PathVariable("id") Long id) {

        // 查询活动信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }

        // 检查活动状态
        if (activity.getStatus() != 0) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目已开始或已结束，无法退出"));
        }

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询用户报名信息
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setActivityId(id);
        signupQuery.setUserId(currentUserId);
        Page<ActivitySignup> signupPage = activitySignupService.queryByPage(signupQuery, PageRequest.of(0, 1));

        if (signupPage.isEmpty()) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "您尚未参与该项目"));
        }

        // 取消报名
        ActivitySignup signup = signupPage.getContent().get(0);
        signup.setStatus(3); // 已取消
        activitySignupService.update(signup);

        return ResponseEntity.ok(ApiResponse.success(true, "退出项目成功"));
    }

    /**
     * 项目统计信息
     *
     * @return 项目统计信息
     */
    @GetMapping("/projects/stats")
    public ResponseEntity<ApiResponse<ProjectStatsDTO>> getProjectStats() {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 创建统计DTO
        ProjectStatsDTO statsDTO = new ProjectStatsDTO();

        // 查询正在参与的项目数
        ActivitySignup participatingQuery = new ActivitySignup();
        participatingQuery.setUserId(currentUserId);
        participatingQuery.setStatus(1); // 已通过
        long participatingCount = activitySignupService.count(participatingQuery);
        statsDTO.setParticipatingCount((int) participatingCount);

        // 查询已完成的项目数
        ActivitySignup completedQuery = new ActivitySignup();
        completedQuery.setUserId(currentUserId);
        completedQuery.setStatus(1); // 已通过
        // 这里简化处理，实际应该查询已结束的活动
        long completedCount = 0;
        statsDTO.setCompletedCount((int) completedCount);

        // 查询累计服务时长
        // 这里简化处理，实际应该查询志愿者服务记录
        VolunteerInfo volunteerInfo = new VolunteerInfo();
        volunteerInfo.setUserId(currentUserId);
        Page<VolunteerInfo> volunteerInfoPage = volunteerInfoService.queryByPage(volunteerInfo, PageRequest.of(0, 1));

        if (!volunteerInfoPage.isEmpty()) {
            VolunteerInfo info = volunteerInfoPage.getContent().get(0);
            statsDTO.setTotalHours(info.getVolunteerHours() != null ? info.getVolunteerHours() : 0);
        } else {
            statsDTO.setTotalHours(0);
        }

        // 查询平均评分
        // 这里简化处理，实际应该查询活动反馈
        statsDTO.setAverageRating(4.5);

        return ResponseEntity.ok(ApiResponse.success(statsDTO));
    }

    // 移除项目签到方法

    /**
     * 评价项目
     *
     * @param id 项目ID
     * @param ratingDTO 评分信息
     * @return 评价结果
     */
    @PostMapping("/projects/{id}/rate")
    public ResponseEntity<ApiResponse<Void>> rateProject(
            @PathVariable("id") Long id,
            @RequestBody ProjectRatingDTO ratingDTO) {
        // 查询活动信息
        Activity activity = activityService.queryById(id);
        if (activity == null) {
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "项目不存在"));
        }

        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询用户是否已评价
        ActivityFeedback existingFeedback = activityFeedbackService.queryByUserAndActivity(currentUserId, id);

        if (existingFeedback != null) {
            // 更新评价
            existingFeedback.setSatisfaction(ratingDTO.getRating());
            existingFeedback.setContent(ratingDTO.getContent());
            activityFeedbackService.update(existingFeedback);
        } else {
            // 创建新评价
            ActivityFeedback feedback = new ActivityFeedback();
            feedback.setActivityId(id);
            feedback.setUserId(currentUserId);
            feedback.setSatisfaction(ratingDTO.getRating());
            feedback.setContent(ratingDTO.getContent());
            feedback.setCreateTime(new Date());
            activityFeedbackService.insert(feedback);
        }

        return ResponseEntity.ok(ApiResponse.success(null, "评价成功"));
    }

    // 移除项目签到/签退方法

    /**
     * 登记服务时长
     *
     * @param serviceHoursDTO 服务时长信息
     * @return 登记结果
     */
    @PostMapping("/projects/hours")
    public ResponseEntity<ApiResponse<ServiceHoursResponseDTO>> recordServiceHours(@RequestBody ServiceHoursDTO serviceHoursDTO) {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询活动信息
        Activity activity = activityService.queryById(serviceHoursDTO.getProjectId());
        if (activity == null) {
            return ResponseEntity.ok(ApiResponse.error(404, "项目不存在"));
        }

        // 查询用户报名信息
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setActivityId(activity.getId());
        signupQuery.setUserId(currentUserId);
        List<ActivitySignup> signups = activitySignupService.queryAll(signupQuery);

        if (signups.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.error(403, "您尚未报名该项目，无法登记服务时长"));
        }

        // 验证服务时长
        if (serviceHoursDTO.getHours() == null || serviceHoursDTO.getHours() <= 0 || serviceHoursDTO.getHours() > 24) {
            return ResponseEntity.ok(ApiResponse.error(400, "服务时长必须在 1-24 小时之间"));
        }

        // 创建服务记录
        VolunteerServiceRecord serviceRecord = new VolunteerServiceRecord();
        serviceRecord.setVolunteerId(currentUserId);
        serviceRecord.setActivityId(activity.getId());
        serviceRecord.setServiceHours(serviceHoursDTO.getHours());

        // 处理日期
        try {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date serviceDate = dateFormat.parse(serviceHoursDTO.getDate());
            serviceRecord.setServiceDate(serviceDate);
        } catch (ParseException e) {
            return ResponseEntity.ok(ApiResponse.error(400, "日期格式不正确，请使用 YYYY-MM-DD 格式"));
        }

        serviceRecord.setDescription(serviceHoursDTO.getDescription());
        serviceRecord.setStatus(0); // 待审核
        serviceRecord.setCreateTime(new Date());

        // 保存服务记录
        VolunteerServiceRecord savedRecord = volunteerServiceRecordService.insert(serviceRecord);

        // 构建响应
        ServiceHoursResponseDTO responseDTO = new ServiceHoursResponseDTO();
        responseDTO.setId(savedRecord.getId());
        responseDTO.setProjectId(activity.getId());
        responseDTO.setHours(savedRecord.getServiceHours());
        responseDTO.setDate(serviceHoursDTO.getDate());
        responseDTO.setStatus(savedRecord.getStatus());

        return ResponseEntity.ok(ApiResponse.success(responseDTO));
    }

    /**
     * 评价项目
     *
     * @param ratingDTO 评价信息
     * @return 评价结果
     */
    @PostMapping("/rate")
    public ResponseEntity<ApiResponse<ProjectRatingResponseDTO>> rateProject(@RequestBody ProjectRatingRequestDTO ratingDTO) {
        // 获取当前用户ID
        Long currentUserId = getCurrentUserId();

        // 查询活动信息
        Activity activity = activityService.queryById(ratingDTO.getProjectId());
        if (activity == null) {
            return ResponseEntity.ok(ApiResponse.error(404, "项目不存在"));
        }

        // 查询用户报名信息
        ActivitySignup signupQuery = new ActivitySignup();
        signupQuery.setActivityId(activity.getId());
        signupQuery.setUserId(currentUserId);
        List<ActivitySignup> signups = activitySignupService.queryAll(signupQuery);

        if (signups.isEmpty()) {
            return ResponseEntity.ok(ApiResponse.error(403, "您尚未报名该项目，无法评价"));
        }

        // 验证评分
        if (ratingDTO.getRating() == null || ratingDTO.getRating() < 1 || ratingDTO.getRating() > 5) {
            return ResponseEntity.ok(ApiResponse.error(400, "评分必须在 1-5 之间"));
        }

        // 查询是否已经评价过
        ActivityFeedback existingFeedback = activityFeedbackService.queryByUserAndActivity(currentUserId, activity.getId());
        ActivityFeedback feedback;

        if (existingFeedback != null) {
            // 更新现有评价
            feedback = existingFeedback;
            feedback.setSatisfaction(ratingDTO.getRating());
            feedback.setContent(ratingDTO.getContent());
            feedback.setUpdateTime(new Date());
            activityFeedbackService.update(feedback);
        } else {
            // 创建新评价
            feedback = new ActivityFeedback();
            feedback.setUserId(currentUserId);
            feedback.setActivityId(activity.getId());
            feedback.setSatisfaction(ratingDTO.getRating());
            feedback.setContent(ratingDTO.getContent());
            feedback.setCreateTime(new Date());
            feedback = activityFeedbackService.insert(feedback);
        }

        // 构建响应
        ProjectRatingResponseDTO responseDTO = new ProjectRatingResponseDTO();
        responseDTO.setId(feedback.getId());
        responseDTO.setProjectId(activity.getId());
        responseDTO.setRating(feedback.getSatisfaction());
        responseDTO.setContent(feedback.getContent());
        responseDTO.setTime(feedback.getCreateTime());

        return ResponseEntity.ok(ApiResponse.success(responseDTO));
    }

    /**
     * 获取当前登录用户的ID
     *
     * @return 当前用户ID
     */
    private Long getCurrentUserId() {
        // 从SecurityContextHolder获取当前认证信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            // 获取用户名
            String username = authentication.getName();
            // 通过用户名查询用户信息
            User user = userMapper.findByUsername(username);
            if (user != null) {
                return user.getId();
            }
        }
        // 如果无法获取用户信息，抛出异常
        throw new RuntimeException("未能获取当前用户信息，请确保用户已登录");
    }
}